const urls = [
  'https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg',
  'https://www.kkkk1000.com/images/getImgData/gray.gif',
  'https://www.kkkk1000.com/images/getImgData/Particle.gif',
  'https://www.kkkk1000.com/images/getImgData/arithmetic.png',
  'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif',
  'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg',
  'https://www.kkkk1000.com/images/getImgData/arithmetic.gif',
  'https://www.kkkk1000.com/images/wxQrCode2.png',
  'https://www.kkkk1000.com/images/getImgData/getImgDatadata.jpg',
  'https://www.kkkk1000.com/images/getImgData/gray.gif',
  'https://www.kkkk1000.com/images/getImgData/Particle.gif',
  'https://www.kkkk1000.com/images/getImgData/arithmetic.png',
  'https://www.kkkk1000.com/images/getImgData/arithmetic2.gif',
  'https://www.kkkk1000.com/images/getImgData/getImgDataError.jpg',
  'https://www.kkkk1000.com/images/getImgData/arithmetic.gif',
  'https://www.kkkk1000.com/images/wxQrCode2.png'
]
//此处有一个图片数组，写一个imageload的方法，使用Promise
//写一个函数，控制同时下载的图片数不超过3个，直到把图片下载完

function imageload(url) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = url
    img.onload = function() {
      console.log('一张图片加载完成')
      resolve()
    }
    img.onerror = reject
    console.log(img.src);
  })
}

function limitLoad(urls, handler, limit) {
  const urlArr = [].concat(urls)
  let promiseList = []

  promiseList = urlArr.splice(0, limit).map((url, index) => {
    return handler(url).then(() => {
      return index
    })
  })

  console.log(promiseList)

  return urlArr.reduce((last, url, currentIndex) => {
    return last.then(() => {
      return Promise.race(promiseList)
    })
    .catch(err => {
      console.log(err)
    })
    .then(res => {
      promiseList[res] = handler(urlArr[currentIndex]).then(() => {
        return res
      })
    })
  }, Promise.resolve())
  .then(() => {
    return Promise.all(promiseList)
  })
}

limitLoad(urls, imageload, 3).then(res => {
  console.log('所有图片加载完成')
})